package com.example.flowermall.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.flowermall.constants.Constant;
import com.example.flowermall.entity.Invitaton;
import com.example.flowermall.entity.Result;
import com.example.flowermall.entity.User;
import com.example.flowermall.service.IUserService;
import com.example.flowermall.util.RedisUtil;
import com.example.flowermall.util.UploadFileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author xiaoman
 * @since 2023-05-30
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    IUserService userService;
    @Autowired
    PasswordEncoder passwordEncoder;
    @Autowired
    RedisUtil redisUtil;
    @Value("${uploadUrl.url}")
    private String url;
    @GetMapping("/list")
    public Result select(@RequestParam(value = "username",required = false)String username,
                         @RequestParam(value = "pageNo",required = false)Long pageNo,
                         @RequestParam(value = "pageSize",required = false)Long pageSize){
        LambdaQueryWrapper<User> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(StringUtils.hasLength(username),User::getUsername,username);
        Page<User> page=new Page<>(pageNo,pageSize);
        userService.page(page, queryWrapper);
        List<User> records = page.getRecords();
        if(!ObjectUtils.isEmpty(records)){
            for(User user : records){
                List<User> beCode = userService.getBeCode(user.getInvitationCode());
                user.setUserList(beCode);
                User inviteUser = userService.getInvitationCode(user.getBeInvitedCode());
                user.setUsers(inviteUser);
            }
        }
        Result result=Result.success();
        Map<String,Object> data=new HashMap<>();
        data.put("total",page.getTotal());
        data.put("rows",page.getRecords());
        result.put("data",data);
        return result;
    }
    @GetMapping("/lists")
    public Result selectUser(@RequestParam(value = "username",required = false)String username){
        List<User> user = userService.selectUsers(username);
        Result result=Result.success();
        result.put("data",user);
        return result;
    }

    @PostMapping
    public Result addUser(@RequestBody User user){
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        userService.addUser(user);
        return Result.success("添加用户成功");

    }
    @DeleteMapping("/{id}")
    public Result deleteById(@PathVariable ("id")Integer id){
        userService.delete(id);
        return Result.success("删除用户成功");
    }
    @GetMapping("/{id}")
    public Result getUserById(@PathVariable("id") Integer id){
        User userById = userService.getUserById(id);
        Result result=Result.success();
        result.put("data",userById);
        return result;
    }
    @PutMapping("/update")
    public Result updateUser(@RequestBody User user){
        if(!ObjectUtils.isEmpty(user.getPassword())){
            user.setPassword(passwordEncoder.encode(user.getPassword()));
        }
        userService.updateUser(user);
        return  Result.success("修改用户成功");
    }
    @PostMapping("/uploads")
    public Result upload(HttpServletRequest request,  MultipartFile file) throws URISyntaxException {
        String suffixName = UploadFileUtils.getSuffixName(file);
        String newFileName = UploadFileUtils.getNewFileName(suffixName);
        //String path = "D:/java"+ "/upload/";
        String path = "/opt/wechat-app"+ "/upload/";
        //String realPath = path.replace('/', '\\');
        //realPath：服务器物理存储地址
        File fileDirectory = new File(path);
        File destFile = new File(path + newFileName);  //创建文件
        try {
            if (!fileDirectory.exists() && !fileDirectory.mkdirs()) {
                throw new IOException("文件夹创建失败,路径为：" + fileDirectory);
            }
            file.transferTo(destFile);

            //URI uri = UploadFileUtils.getHost(new URI(request.getRequestURL() + ""));
            String sqlImg = url + Constant.RESOURCE+ "/upload/" + newFileName;  //sqlImg：数据库存储地址
            Result result=Result.success();
            result.put("imgPath",sqlImg);
            return result;
        } catch (IOException e) {
            e.printStackTrace();
            return Result.error("异常");
        }
    }

    @GetMapping("/invitationList/{id}")
    public Result getInvitationList(@PathVariable ("id")Integer id){
        List<Invitaton> invitationList = userService.getInvitationList(id);
        Result result = Result.success();
        result.put("data",invitationList);
        return  result;
    }

    @DeleteMapping("/invitation/{id}")
    public Result payouts(@PathVariable ("id")Integer id){
        Boolean payouts = userService.payouts(id);
        if(payouts){
            return Result.success("提现成功");
        }
        return Result.error("提现失败");
    }

}
